/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sys.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.entity.Menu;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.service.MenuService;
import com.jeeplus.modules.sys.service.RoleService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单Controller
 *
 * @author jeeplus
 * @version 2016-3-23
 */

@RestController
@RequestMapping("/sys/menu")
public class MenuController extends BaseController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;

    @ModelAttribute("menu")
    public Menu get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return menuService.get(id);
        } else {
            return new Menu();
        }
    }

    @RequiresPermissions("sys:menu:list")
    @GetMapping("list")
    public AjaxJson list() {
         List<Menu> menus = Lists.newArrayList();
        for(Menu menu: menuService.findAllMenu()){
            if(!"1".equals(menu.getId())){
                menus.add(menu);
            }
        }
        return AjaxJson.success().put("menuList", menus);
    }

    @RequiresPermissions(value = {"sys:menu:view", "sys:menu:add", "sys:menu:edit"}, logical = Logical.OR)
    @GetMapping("queryById")
    public AjaxJson queryById(Menu menu) {
        if (menu.getParent() == null || menu.getParent().getId() == null) {
            menu.setParent(new Menu(Menu.getRootId()));
        }
        menu.setParent(menuService.get(menu.getParent().getId()));
        return AjaxJson.success().put("menu", menu);
    }

    @RequiresPermissions(value = {"sys:menu:add", "sys:menu:edit"}, logical = Logical.OR)
    @PostMapping("save")
    public AjaxJson save(Menu menu) {
        if (!UserUtils.getUser().isAdmin()) {
            return AjaxJson.error("越权操作，只有超级管理员才能添加或修改数据！");
        }
        if (jeePlusProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(menu);
        if (StringUtils.isNotBlank(errMsg)) {
            return AjaxJson.error(errMsg);
        }

        // 获取排序号，最末节点排序号+30
        if (StringUtils.isBlank(menu.getId())) {
            List<Menu> list = Lists.newArrayList();
            List<Menu> sourcelist = menuService.findAllMenu();
            Menu.sortList(list, sourcelist, menu.getParentId(), false);
            if (list.size() > 0) {
                menu.setSort(list.get(list.size() - 1).getSort() + 30);
            }
        }
        menuService.saveMenu(menu);

        return AjaxJson.success("保存成功!");
    }

    @RequiresPermissions("sys:menu:del")
    @DeleteMapping("delete")
    public AjaxJson delete(Menu menu) {
        AjaxJson j = new AjaxJson();
        if (jeePlusProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作");
        }
        menuService.delete(menu);
        return AjaxJson.success("删除成功!");
    }


    /**
     * 修改菜单排序
     */
    @RequiresPermissions("sys:menu:updateSort")
    @PostMapping("sort")
    public AjaxJson sort(String id1, int sort1, String id2, int sort2) {
        AjaxJson j = new AjaxJson();
        if (jeePlusProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        Menu menu = new Menu();
        menu.setId(id1);
        menu.setSort(sort1);
        menuService.updateSort(menu);
        menu.setId(id2);
        menu.setSort(sort2);
        menuService.updateSort(menu);
        return AjaxJson.success("排序成功！");
    }

    @GetMapping("getChildren")
    public List<Menu> getChildren(String parentId) {
        if ("-1".equals(parentId)) {
            parentId = "1";
        }
        return menuService.getChildren(parentId);
    }


    public List<Menu> getTreeMenu(List<Menu> list, String roleId, String extId, String isShowHid) {
        List rootTree = Lists.newArrayList();
        Menu menu = menuService.get("1");
        getChildOfTree(menu, list, extId, isShowHid);
        rootTree.add(menu);
        return rootTree;
    }

    private Menu getChildOfTree(Menu menuItem, List<Menu> menuList, String extId, String isShowHide) {
        menuItem.setChildren(Lists.newArrayList());
        for (Menu child : menuList) {
            if (StringUtils.isBlank(extId) || (extId != null && !extId.equals(child.getId()) && child.getParentIds().indexOf("," + extId + ",") == -1)) {
                if (isShowHide != null && isShowHide.equals("0") && child.getIsShow().equals("0")) {
                    continue;
                }
                if (child.getParentId().equals(menuItem.getId())) {
                    menuItem.getChildren().add(getChildOfTree(child, menuList, extId, isShowHide));
                }
            }
        }
        return menuItem;
    }

    /**
     * isShowHide是否显示隐藏菜单
     *
     * @param extId
     * @return
     */
    @RequiresPermissions("user")
    @GetMapping("treeData")
    public AjaxJson treeData(@RequestParam(required = false) String roleId, @RequestParam(required = false) String extId, @RequestParam(required = false) String isShowHide) {
        List<Menu> list = menuService.findAllMenu();
        List rootTree = getTreeMenu(list, roleId, extId, isShowHide);
        Role role = roleService.get(roleId);
        String menuIds = "";
        if (role != null) {
            menuIds = "," + role.getMenuIds() + ",";
        }
        return AjaxJson.success().put("treeData", rootTree).put("selected", menuIds);
    }

    /**
     * isShowHide是否显示隐藏菜单
     *
     * @return
     */
    @RequiresPermissions("user")
    @GetMapping("treeData2")
    public AjaxJson treeData2() {
        List<Menu> list = menuService.findAllMenu();
        List<Menu> rootTree = getTreeMenu(list, "", "", "");
        return AjaxJson.success().put("treeData", rootTree.get(0).getChildren());
    }

}
